/*
 * UpdatePasswordServlet.java
 * 作用：处理用户修改密码的请求，验证新密码并更新数据库。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.UserDao;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/updatePassword")
public class UpdatePasswordServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("user");

        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        if (newPassword == null || newPassword.isEmpty() || !newPassword.equals(confirmPassword)) {
            request.getSession().setAttribute("message", "密码更新失败：两次输入的密码不一致或密码为空。");
            response.sendRedirect(request.getContextPath() + "/user/profile");
            return;
        }

        user.setPassword(newPassword); // 在实际项目中应加密
        userDao.updateUser(user); // updateUser 需要能处理密码更新

        request.getSession().setAttribute("message", "密码更新成功！");
        response.sendRedirect(request.getContextPath() + "/user/profile");
    }
} 